package com.wnxy.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wnxy.admin.dto.ChargeRealTimeDto;
import com.wnxy.admin.dto.ChargingPileRealTimeDto;
import com.wnxy.admin.dto.ChargingStationDto;
import com.wnxy.admin.entity.ChargingPile;
import com.wnxy.admin.entity.ChargingStation;
import com.wnxy.admin.entity.Order;
import com.wnxy.admin.mapper.ChargingPileMapper;
import com.wnxy.admin.mapper.ChargingStationMapper;
import com.wnxy.admin.mapper.OrderMapper;
import com.wnxy.admin.service.IChargingStationRealTimeService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 充电站--实时监控模块 服务实现类
 * </p>
 *
 * @author nhj
 */

@Service
public class ChargingStationRealTimeServiceImpl implements IChargingStationRealTimeService {

    private final ChargingStationMapper chargingStationMapper;
    private final ChargingPileMapper chargingPileMapper;
    private final ElasticsearchRestTemplate elasticsearchRestTemplate;
    private final OrderMapper orderMapper;

    public ChargingStationRealTimeServiceImpl(ChargingStationMapper chargingStationMapper, ChargingPileMapper chargingPileMapper, ElasticsearchRestTemplate elasticsearchRestTemplate, OrderMapper orderMapper) {
        this.chargingStationMapper = chargingStationMapper;
        this.chargingPileMapper = chargingPileMapper;
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
        this.orderMapper = orderMapper;
    }
    //查询电站下属的电桩--分页
    @Override
    public  PageInfo<ChargingPileRealTimeDto> getChargeById(Long id,Integer pageNum, Integer pageSize,Integer pileSort) {

        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<ChargingPile> queryWrapper = Wrappers.lambdaQuery(ChargingPile.class);

        //充电桩类别1:汽车充电桩2:电瓶车充电桩3:大型公交车充电桩
        if (pileSort !=null ){
            queryWrapper.eq(ChargingPile::getChargingPileSort,pileSort);
        }

        List<ChargingPile> chargingPiles = chargingPileMapper.selectList(queryWrapper.eq(ChargingPile::getChargingStationId,id));

        //复制给dto
        List<ChargingPileRealTimeDto> collect = chargingPiles.stream().map(c -> {

            ChargingPileRealTimeDto dto = new ChargingPileRealTimeDto();
            BeanUtil.copyProperties(c, dto);
            //订单表(三个条件--状态已结束--今日--电桩编号)
            List<Order> orders = orderMapper.selectList(Wrappers.lambdaQuery(Order.class).
                    eq(Order::getChargingPileNumber, c.getChargingPileNumber()));

            if (orders.size()!=0){
                BigDecimal totalChargeAmount = orders.stream()
                        .map(Order::getChargeAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                dto.setClientVolume(orders.size()+" 人");
                dto.setChargeAmount(totalChargeAmount+" Kwh");
                return dto;
            }

            dto.setClientVolume("0 人");
            dto.setChargeAmount("0 Kwh");

            return dto;
        }).collect(Collectors.toList());

        PageInfo<ChargingPileRealTimeDto> chargingPileRealTimeDtoPageInfo = new PageInfo<>(collect);

        return chargingPileRealTimeDtoPageInfo;
    }


    @Override
    public List<ChargingStationDto> queryKeyword(String searchContext) {

        //构建查询对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        builder.withQuery(QueryBuilders.multiMatchQuery(searchContext,
                "chargingStationName"));

        SearchHits<ChargingStationDto> search =
                elasticsearchRestTemplate.search(builder.build(), ChargingStationDto.class);

        List<ChargingStationDto> collect = search.getSearchHits().stream()
                .map(e -> e.getContent()).collect(Collectors.toList());

        return collect;
    }


    //根据ID获取充电站
    @Override
    public ChargeRealTimeDto getChargeRealTim(Long id) {

        //根据id查询电站
        ChargingStation chargingStation = chargingStationMapper.selectOne(Wrappers.lambdaQuery(ChargingStation.class)
                .eq(ChargingStation::getId, id));

        //订单表(三个条件--状态已结束--今日--电站id)
        List<Order> orders = orderMapper.selectList(Wrappers.lambdaQuery(Order.class)
                .eq(Order::getChargingStationId, id));

        if (orders.size()==0){

            ChargeRealTimeDto chargeRealTimeDto = new ChargeRealTimeDto();

            BeanUtil.copyProperties(chargingStation, chargeRealTimeDto);
            chargeRealTimeDto.setEnterAccountTotal( "0 元");
            chargeRealTimeDto.setClientVolumeTotal("0 人");
            chargeRealTimeDto.setChargingPrice("0 /kwh");

            return chargeRealTimeDto;
        }

        List<BigDecimal> amounts = orders.stream().map(o -> o.getAmount()).collect(Collectors.toList());
        List<BigDecimal> chargeAmounts = orders.stream().map(o -> o.getChargeAmount()).collect(Collectors.toList());

        //充电站今日总收款--
        BigDecimal total = BigDecimal.ZERO;
        for (BigDecimal amount : amounts) {
            total = total.add(amount);
        }

        //充电站今日总电量--
        BigDecimal chargeTotal = BigDecimal.ZERO;
        for (BigDecimal amount : chargeAmounts) {

            chargeTotal = chargeTotal.add(amount);
        }

        //单价
        BigDecimal chargingPrice = total.divide(chargeTotal, 2, BigDecimal.ROUND_HALF_UP);

        //组装电站
        ChargeRealTimeDto chargeRealTimeDto = new ChargeRealTimeDto();

        BeanUtil.copyProperties(chargingStation, chargeRealTimeDto);
        chargeRealTimeDto.setEnterAccountTotal(total +" 元");
        chargeRealTimeDto.setClientVolumeTotal(orders.size()+" 人");
        chargeRealTimeDto.setChargingPrice(chargingPrice+" /kwh");

        return chargeRealTimeDto;
    }



    //获取充电站 --地图显示
    @Override
    public List<ChargingStationDto> getAllChargingStation() {
        // BeanUtil.copyProperties();

        List<ChargingStation> chargingStations =
                chargingStationMapper.selectList(Wrappers.lambdaQuery(ChargingStation.class));

        List<ChargingStationDto> collect = chargingStations.stream()
                .filter(c -> c.getCoordinate() != null && !c.getCoordinate().isEmpty() && c.getCoordinate().contains(","))
                .map(c -> {
                    ChargingStationDto dto = new ChargingStationDto();
                    BeanUtil.copyProperties(c, dto);
                    dto.setChargingStationState(c.getChargingStationState() == 1 ? "营业中" : "歇业");
                    return dto;
                })
                .collect(Collectors.toList());

        //将数据加到es中
        elasticsearchRestTemplate.save(collect);

        return collect;
    }


}
